package com.yuyou.fn.controller;


import com.alibaba.fastjson.JSON;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.Principals;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.*;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.educational.vo.*;
import com.yuyou.fn.platform.entity.CustomerUser;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.portal.entity.AdConfig;
import com.yuyou.fn.portal.entity.CourseDisplayConfig;
import com.yuyou.fn.portal.entity.OuterFeedback;
import com.yuyou.fn.portal.service.IConfigService;
import com.yuyou.fn.portal.service.IOuterFeedbackService;
import com.yuyou.fn.portal.service.IOuterShoppingcartService;
import com.yuyou.fn.portal.service.IShoppingCartDetailService;
import com.yuyou.fn.portal.vo.ShoppingCartDetailQueryVo;
import com.yuyou.fn.portal.vo.ShoppingCartSituationVo;
import com.yuyou.fn.util.Webs;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/admin/online")
public class AdminOnlineController extends ApiBaseController {

    @Resource
    private IExternalMeasureScoreService externalMeasureScoreService;

    @Resource
    private IConfigService configService;

    @Resource
    private IPeriodService periodService;

    @Resource
    private ICampusService campusService;

    @Resource
    private IBaseGradeService baseGradeService;

    @Resource
    private ICustomerUserService customerUserService;

    @Resource
    private ICustomerBindStudentService customerBindStudentService;

    @Resource
    private IOuterFeedbackService outerFeedbackService;

    @Resource
    private IClassExpandDetailService classExpandDetailService;

    @Resource
    private IDegreeSubscribeService degreeSubscribeService;

    @Resource
    private IShoppingCartDetailService shoppingCartDetailService;

    @Resource
    private IChargeSettingService chargeSettingService;

    @ApiOperation("新增分段设置")
    @RequestMapping(value = "/addChargeSetting", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> addChargeSetting(@ModelAttribute @Valid ChargeSettingSaveUpdateVo  chargeSettingSaveUpdateVo) throws IOException {
        chargeSettingService.saveOrUpdateChargeSettingByVo(chargeSettingSaveUpdateVo);
        return ReturnResult.success("ok");
    }

    @ApiOperation("更新分段设置")
    @RequestMapping(value = "/updateChargeSetting", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> updateChargeSetting(@Valid @ModelAttribute ChargeSettingSaveUpdateVo  chargeSettingSaveUpdateVo) throws IOException {
        if (chargeSettingSaveUpdateVo.getChargeSettingId()==null){
            throw new BusException("id必传");
        }
        chargeSettingService.saveOrUpdateChargeSettingByVo(chargeSettingSaveUpdateVo);
        return ReturnResult.success("ok");
    }

    @ApiOperation("单个分段设置详情")
    @RequestMapping(value = "/chargeSettingDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<ChargeSetting> chargeSettingDetail(@ApiParam("唯一标识")@RequestParam("chargeSettingId") long chargeSettingId) throws IOException {
        ChargeSetting chargeSetting = chargeSettingService.findById(chargeSettingId);
        return ReturnResult.success(chargeSetting);
    }

    @ApiOperation("分段设置列表")
    @RequestMapping(value = "/chargeSettingPage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ChargeSetting>> chargeSettingPage(@ModelAttribute ChargeSettingQueryVo chargeSettingQueryVo,@RequestParam(value = "pageNo") int pageNo, @RequestParam(value = "pageSize") int pageSize) throws IOException {
        Page<ChargeSetting> page=chargeSettingService.findChargeSettingPageByQueryVo(chargeSettingQueryVo,pageNo,pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("学生外部成绩")
    @RequestMapping(value = "/externalMeasureScoreList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> externalMeasureScoreList(@ModelAttribute ExternalMeasureScoreQueryVo externalMeasureScoreQueryVo, @RequestParam(value = "pageNo") int pageNo, @RequestParam(value = "pageSize") int pageSize) throws IOException {
        Page<ExternalMeasureScore> page = externalMeasureScoreService.findByQuery(externalMeasureScoreQueryVo, pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("导出学生外部成绩")
    @RequestMapping(value = "/exportExternalMeasureScoreList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void exportDiscountCodeList(@ModelAttribute ExternalMeasureScoreQueryVo externalMeasureScoreQueryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {

        Page<ExternalMeasureScore> page = externalMeasureScoreService.findByQuery(externalMeasureScoreQueryVo, 1, 10 * 1024);

        SXSSFWorkbook excel = new SXSSFWorkbook();

        SXSSFSheet sheet = excel.createSheet("学生成绩");

        SXSSFRow firstRow = sheet.createRow(0);

        String[] titles = new String[]{"姓名", "手机号", "年级", "科目", "中考单科分数", "学业诊断名次", "录入时间"};

        for (int i = 0; i < titles.length; i++) {

            SXSSFCell cell = firstRow.createCell(i);
            cell.setCellValue(titles[i]);
        }

        List<ExternalMeasureScore> externalMeasureScores = page.getRecords();

        for (int i = 0; i < externalMeasureScores.size(); i++) {

            SXSSFRow row = sheet.createRow(i + 1);

            ExternalMeasureScore externalMeasureScore = externalMeasureScores.get(i);

            int c = 0;
            SXSSFCell cell = row.createCell(c++);
            cell.setCellValue(externalMeasureScore.getStudentName());

            cell = row.createCell(c++);
            cell.setCellValue(externalMeasureScore.getStudentPhoneNo());

            cell = row.createCell(c++);
            cell.setCellValue(externalMeasureScore.getGradeName());

            cell = row.createCell(c++);
            cell.setCellValue(externalMeasureScore.getSubjectName());

            cell = row.createCell(c++);
            if (externalMeasureScore.getScoreType() != null && externalMeasureScore.getScoreType() == 1) {
                cell.setCellValue(externalMeasureScore.getScore());
            } else {
                cell.setCellValue(StringUtils.EMPTY);
            }

            cell = row.createCell(c++);
            if (externalMeasureScore.getScoreType() != null && externalMeasureScore.getScoreType() == 2) {
                cell.setCellValue(externalMeasureScore.getScore());
            } else {
                cell.setCellValue(StringUtils.EMPTY);
            }

            cell = row.createCell(c++);
            cell.setCellValue(Utils.formatDate(externalMeasureScore.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));

        }
        Webs.writeExcel(request, response, excel, "学生成绩");

    }

    @ApiOperation("广告设置list")
    @RequestMapping(value = "/adConfigList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<AdConfig>> adConfigList(@RequestParam("areaTeamId") Long areaTeamId) throws IOException {
        return ReturnResult.success(configService.findAdConfigByAreaTeamId(areaTeamId));
    }

    @ApiOperation("添加广告设置")
    @RequestMapping(value = "/addAdConfig", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> addAdConfig(@RequestParam(value = "areaTeamId", required = true) Long areaTeamId, @RequestParam("page") String page, @RequestParam("position") String position, @RequestParam("picUrl") String picUrl, @RequestParam("clickUrl") String clickUrl) throws IOException {
        configService.addAdConfig(areaTeamId, page, position, picUrl, clickUrl, Principals.get());
        return ReturnResult.success("OK");
    }

    @ApiOperation("更新广告设置")
    @RequestMapping(value = "/updateAdConfig", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> updateAdConfig(@RequestParam(value = "adId", required = true) Long adId, @RequestParam("page") String page, @RequestParam("position") String position, @RequestParam("picUrl") String picUrl, @RequestParam("clickUrl") String clickUrl) throws IOException {
        configService.updateAdConfig(adId, page, position, picUrl, clickUrl, Principals.get());
        return ReturnResult.success("OK");
    }

    @ApiOperation("获取广告设置")
    @RequestMapping(value = "/adConfig", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<AdConfig> adConfig(@RequestParam(value = "adId", required = true) Long adId) throws IOException {
        AdConfig adConfig = configService.findAdConfigById(adId);
        return ReturnResult.success(adConfig);
    }

    @ApiOperation("删除广告设置")
    @RequestMapping(value = "/delAdConfig", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> delAdConfig(@RequestParam(value = "adId", required = true) Long adId) throws IOException {
        configService.delAdConfig(adId);
        return ReturnResult.success("OK");
    }

    @ApiOperation("课程显示设置list")
    @RequestMapping(value = "/courseDisplayConfigList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<CourseDisplayConfig>> courseDisplayConfigList(@RequestParam(value = "areaTeamId", required = true) Long areaTeamId) throws IOException {
        List<CourseDisplayConfig> courseDisplayConfigs = configService.findCourseDisplayByAreaTeamId(areaTeamId);
        return ReturnResult.success(courseDisplayConfigs);
    }

    @ApiOperation("保存课程显示设置")
    @RequestMapping(value = "/saveDisplayConfig", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveDisplayConfig(@RequestParam("config") String config) throws IOException {
        CourseDisplayConfig courseDisplayConfig = JSON.parseObject(config, CourseDisplayConfig.class);
        configService.updateCourseDisplayConfig(courseDisplayConfig, Principals.get());
        return ReturnResult.success("OK");
    }

    @ApiOperation("课程显示设置")
    @RequestMapping(value = "/displayConfig", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<CourseDisplayConfig> displayConfig(@RequestParam(value = "areaTeamId", required = true) Long areaTeamId) throws IOException {
        CourseDisplayConfig courseDisplayConfig = configService.findCourseDisplayConfig(areaTeamId);
        return ReturnResult.success(courseDisplayConfig);
    }


    @ApiOperation("期数&校区&年级配置")
    @RequestMapping(value = "/periodCampusGradeForCourseDisplayConfig", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Map<String, Object>> periodCampusForCourseDisplayConfig(@RequestParam(value = "areaTeamId", required = true) Long areaTeamId) throws IOException {
        List<Period> periods = periodService.findNearPeriod(areaTeamId, 4);
        List<Campus> campuses = campusService.findCampusByAreaTeamId(areaTeamId);
        List<BaseGrade> grades = baseGradeService.findAllFromCache();
        Map<String, Object> ret = Maps.newHashMap();
        ret.put("periods", periods);
        ret.put("campuses", campuses);
        ret.put("grades", grades);
        return ReturnResult.success(ret);
    }


    @ApiOperation("注册用户")
    @RequestMapping(value = "/customerUserList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CustomerUser>> customerUserList(@RequestParam(value = "phoneNo", required = false) String phoneNo, @RequestParam(value = "pageNo") int pageNo, @RequestParam(value = "pageSize") int pageSize) throws IOException {
        Example<CustomerUser> example = CustomerUser.createExample();
        example.orderBy("createTime").desc();
        if (StringUtils.isNotEmpty(phoneNo)) {
            example.createCriteria().andEqualTo("phoneNo", phoneNo);
        }
        Page<CustomerUser> page = customerUserService.findPageByExample(example, pageNo, pageSize);
        if (!page.getRecords().isEmpty()) {
            for (CustomerUser customerUser : page.getRecords()) {
                customerUser.setPassword(null);
            }
        }
        return ReturnResult.success(page);
    }

    @ApiOperation("学员信息List")
    @RequestMapping(value = "/customerBindStudentList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CustomerUser>> customerBindStudentList(@RequestParam(value = "userId", required = true) Long userId) throws IOException {
        List<CustomerBindStudentVo> customerBindStudentVos = customerBindStudentService.findStudentsByUserIds(userId);
        return ReturnResult.success(customerBindStudentVos);
    }

    @ApiOperation("绑定学员")
    @RequestMapping(value = "/bindStudent", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> bindStudent(@RequestParam(value = "userId", required = true) Long userId, @RequestParam("studentName") String studentName, @RequestParam("studentPhoneNo") String studentPhoneNo) throws IOException {
        customerBindStudentService.addBind(userId, studentName, studentPhoneNo);
        return ReturnResult.success("OK");
    }

    @ApiOperation("解绑学员")
    @RequestMapping(value = "/unbindStudent", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> unbindStudent(@RequestParam(value = "userId", required = true) Long userId, @RequestParam(value = "studentId", required = true) Long studentId) throws IOException {
        customerBindStudentService.deleteByStudentIdAndUserId(studentId, userId);
        return ReturnResult.success("OK");
    }


    @ApiOperation("反馈信息List")
    @RequestMapping(value = "/feedbackList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<OuterFeedback>> feedbackList(@RequestParam(value = "username", required = false) String username, @RequestParam(value = "start", required = false) Date start, @RequestParam(value = "end", required = false) Date end, @RequestParam(value = "status", required = false) Integer status, @RequestParam(value = "pageNo") int pageNo, @RequestParam(value = "pageSize") int pageSize) throws IOException {
        Page<OuterFeedback> page = outerFeedbackService.findForPage(username, start, end, status, pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("更改反馈信息状态")
    @RequestMapping(value = "/updateFeedbackStatus", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<OuterFeedback>> updateFeedbackStatus(@RequestParam("outerFeedbackId") Long outerFeedbackId, @RequestParam("status") Integer status, @RequestParam("contact") String contact,@RequestParam("replyContent") String replyContent) throws IOException {
        outerFeedbackService.updateFeedbackStatus(outerFeedbackId, status,contact,replyContent);
        return ReturnResult.success("OK");
    }


    @ApiOperation("线上转班禁用设置列表")
    @RequestMapping(value = "/settingChangeClassPage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ClassExpandDetailVo>> settingChangeClassPage(@ModelAttribute ClassExpandQueryVo classExpandQueryVo, @ModelAttribute CourseClassQueryVo courseClassQueryVo, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, HttpServletRequest request) throws IOException {
        DataPermission dataPermission = this.getDataPermission(request);
        courseClassQueryVo.setStatus(1);
        Page<ClassExpandDetailVo> page = classExpandDetailService.findClassExpandDetail(classExpandQueryVo, courseClassQueryVo, dataPermission, pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("批量更改班级状态")
    @RequestMapping(value = "/updateClassChangeState", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> updateClassChangeState(@RequestParam("classIds") String classIds,
                                                     @ApiParam("是否可以转班，1 可用，0禁用") @RequestParam(value = "changeState", required = false) Integer changeState,
                                                     @ApiParam("是否可以网报， 1可以，0 禁用") @RequestParam(value = "onlineState", required = false) Integer onlineState,
                                                     @ApiParam("是否置顶， 1置顶，0 不置顶") @RequestParam(value = "isRecommend", required = false) Integer isRecommend,
                                                     HttpServletRequest request) throws IOException {
        classExpandDetailService.updateClassState(Utils.toLongIds(classIds), changeState, null, onlineState, isRecommend);
        return ReturnResult.success("ok");
    }

    @ApiOperation("学位预约统计")
    @RequestMapping(value = "/findDegreeSubscribeDetailPage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<DegreeSubscribeDetailVo>> findDegreeSubscribeDetailPage(@ModelAttribute DegreeSubscribeQueryVo degreeSubscribeQueryVo, @ModelAttribute CourseClassQueryVo courseClassQueryVo, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, HttpServletRequest request) throws IOException {
        DataPermission dataPermission = this.getDataPermission(request);
        if (Utils.checkListEmpty(dataPermission.getBusTeamIds())) {
            throw new BusException("无数据权限");
        }
        courseClassQueryVo.setBusTeamIds(dataPermission.getBusTeamIds());
        Page<DegreeSubscribeDetailVo> degreeSubscribeDetailPage = degreeSubscribeService.findDegreeSubscribeDetailPage(degreeSubscribeQueryVo, courseClassQueryVo, pageNo, pageSize);
        return ReturnResult.success(degreeSubscribeDetailPage);
    }

    @ApiOperation("学位预约跟进")
    @RequestMapping(value = "/followDegreeSubscribe", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> findDegreeSubscribeDetailPage(@RequestParam("degreeSubscribeId") Long degreeSubscribeId, HttpServletRequest request) throws IOException {
        degreeSubscribeService.followDegreeSubscribe(degreeSubscribeId);
        return ReturnResult.success("ok");
    }

    @ApiOperation("购物车情况")
    @RequestMapping(value = "/shoppingCartSituation", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ShoppingCartSituationVo>> shoppingCartSituation(@ModelAttribute ShoppingCartDetailQueryVo shoppingCartDetailQueryVo,
            @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, HttpServletRequest request) throws IOException {
        DataPermission dataPermission = this.getDataPermission(request);
        Page<ShoppingCartSituationVo> shoppingCartSituationVoPage = shoppingCartDetailService.findShoppingCartSituation(dataPermission, shoppingCartDetailQueryVo, pageNo, pageSize);

        return ReturnResult.success(shoppingCartSituationVoPage);
    }

    @ApiOperation("导出购物车情况")
    @RequestMapping(value = "/exportShoppingCartSituation", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportShoppingCartSituation(@ModelAttribute ShoppingCartDetailQueryVo shoppingCartDetailQueryVo, HttpServletRequest request,HttpServletResponse response)  throws IOException {
        DataPermission dataPermission = this.getDataPermission(request);
        Webs.writeExcel(request, response, shoppingCartDetailService.exportShoppingCartSituation(dataPermission,shoppingCartDetailQueryVo), "购物车情况");
        return ReturnResult.success("ok");
    }

}
